<template>
  <div class="discussion-detail-page">
    <el-page-header>
      <template slot="content">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item><a href="/discussions">讨论区</a></el-breadcrumb-item>
          <el-breadcrumb-item>讨论详情</el-breadcrumb-item>
        </el-breadcrumb>
      </template>
    </el-page-header>
    
    <div v-if="loading" class="loading-container">
      <el-loading-spinner />
    </div>
    
    <div v-else-if="!discussion" class="error-state">
      <p>讨论不存在或已被删除</p>
      <el-button @click="$router.push('/discussions')">返回讨论列表</el-button>
    </div>
    
    <div v-else>
      <!-- 讨论主体 -->
      <el-card class="discussion-card">
        <div class="discussion-header">
          <h1>{{ discussion.title }}</h1>
          <div class="discussion-meta">
            <el-avatar :size="32" icon="el-icon-user" />
            <span class="author-name">{{ discussion.author }}</span>
            <span class="time-info">{{ formatDate(discussion.createdAt) }}</span>
            <span v-if="discussion.updatedAt && discussion.updatedAt !== discussion.createdAt" class="updated-info">
              (已编辑)
            </span>
          </div>
          
          <div v-if="discussion.package" class="package-link">
            <el-tag type="primary" size="small" @click="viewPackage(discussion.package.id)">
              关联包: {{ discussion.package.name }}
            </el-tag>
          </div>
          
          <div class="discussion-actions" v-if="isAuthor(discussion.author)">
            <el-button type="text" size="small" @click="editDiscussion">编辑</el-button>
            <el-button type="text" size="small" danger @click="deleteDiscussion">删除</el-button>
          </div>
        </div>
        
        <div class="discussion-content">
          <p v-html="formatContent(discussion.content)"></p>
        </div>
      </el-card>
      
      <!-- 评论区域 -->
      <el-card class="comments-card" style="margin-top: 24px;">
        <template slot="header">
          <div class="comments-header">
            <span>评论 ({{ comments.length }})</span>
          </div>
        </template>
        
        <!-- 发表评论 -->
        <div class="comment-form">
          <el-input 
            v-model="commentForm.content"
            type="textarea"
            :rows="3"
            placeholder="写下您的评论..."
          />
          <div style="text-align: right; margin-top: 12px;">
            <el-button type="primary" @click="submitComment">发布评论</el-button>
          </div>
        </div>
        
        <!-- 评论列表 -->
        <div v-if="comments.length === 0" class="no-comments">
          <p>暂无评论，来发表第一条评论吧！</p>
        </div>
        
        <div v-else class="comments-list">
          <div 
            v-for="comment in comments"
            :key="comment.id"
            class="comment-item"
          >
            <el-avatar :size="28" icon="el-icon-user" />
            <div class="comment-content">
              <div class="comment-meta">
                <span class="comment-author">{{ comment.author }}</span>
                <span class="comment-time">{{ formatDate(comment.createdAt) }}</span>
                <span v-if="isAuthor(comment.author)" class="comment-actions">
                  <el-button type="text" size="mini" @click="editComment(comment)">编辑</el-button>
                  <el-button type="text" size="mini" danger @click="deleteComment(comment.id)">删除</el-button>
                </span>
              </div>
              <div v-if="editingCommentId !== comment.id" class="comment-text">
                {{ comment.content }}
              </div>
              <div v-else class="comment-edit">
                <el-input 
                  v-model="editingCommentContent"
                  type="textarea"
                  :rows="2"
                />
                <div style="text-align: right; margin-top: 8px;">
                  <el-button type="text" size="small" @click="cancelEditComment">取消</el-button>
                  <el-button type="primary" size="small" @click="saveEditComment(comment.id)">保存</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 编辑讨论对话框 -->
    <el-dialog 
      title="编辑讨论"
      :visible.sync="editDialogVisible"
      width="700px"
    >
      <el-form 
        ref="editForm"
        :model="editForm"
        :rules="discussionRules"
        label-width="80px"
      >
        <el-form-item label="关联包">
          <el-select 
            v-model="editForm.packageId"
            placeholder="选择关联的npm包（可选）"
          >
            <el-option label="无关联包" value="" />
            <el-option 
              v-for="pkg in packages"
              :key="pkg.id"
              :label="pkg.name"
              :value="pkg.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入讨论标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="editForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入讨论内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveDiscussion">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'DiscussionDetailPage',
  layout: 'default',
  data() {
    return {
      discussion: null,
      comments: [],
      packages: [],
      loading: false,
      
      // 评论表单
      commentForm: {
        content: ''
      },
      
      // 编辑评论相关
      editingCommentId: null,
      editingCommentContent: '',
      
      // 编辑讨论对话框
      editDialogVisible: false,
      editForm: {
        packageId: '',
        title: '',
        content: ''
      },
      discussionRules: {
        title: [
          { required: true, message: '请输入讨论标题', trigger: 'blur' },
          { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入讨论内容', trigger: 'blur' },
          { min: 10, max: 2000, message: '内容长度在 10 到 2000 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  async fetch() {
    await this.loadDiscussionDetail()
    await this.loadPackages()
  },
  watch: {
    '$route.params.id': {
      handler() {
        this.loadDiscussionDetail()
      },
      immediate: false
    }
  },
  methods: {
    async loadDiscussionDetail() {
      this.loading = true
      try {
        const response = await this.$axios.get(`/discussions/${this.$route.params.id}`)
        this.discussion = response.data
        
        // 加载评论
        await this.loadComments()
      } catch (error) {
        this.$message.error('加载讨论详情失败：' + error.message)
        this.discussion = null
      } finally {
        this.loading = false
      }
    },
    
    async loadComments() {
      try {
        const response = await this.$axios.get(`/discussions/${this.$route.params.id}/comments`)
        this.comments = response.data || []
      } catch (error) {
        this.$message.error('加载评论失败：' + error.message)
        this.comments = []
      }
    },
    
    async loadPackages() {
      try {
        const response = await this.$axios.get('/packages', {
          params: { pageSize: 100 }
        })
        this.packages = response.data.items || []
      } catch (error) {
        this.$message.error('加载包列表失败：' + error.message)
        this.packages = []
      }
    },
    
    formatDate(dateString) {
      if (!dateString) return '未知'
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    
    formatContent(content) {
      // 简单的内容格式化，实际应用中可以使用更复杂的富文本渲染
      if (!content) return ''
      return content
        .replace(/\n/g, '<br>')
        .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.+?)\*/g, '<em>$1</em>')
    },
    
    isAuthor(author) {
      // 在实际应用中，这里应该检查当前登录用户是否是作者
      // 这里简单假设当前用户是 'admin'
      return author === 'admin'
    },
    
    viewPackage(packageId) {
      this.$router.push(`/packages/${packageId}`)
    },
    
    // 评论相关方法
    async submitComment() {
      if (!this.commentForm.content.trim()) {
        this.$message.warning('请输入评论内容')
        return
      }
      
      try {
        const response = await this.$axios.post(`/discussions/${this.$route.params.id}/comments`, {
          content: this.commentForm.content
        })
        
        this.comments.push(response.data)
        this.commentForm.content = ''
        this.$message.success('评论发布成功')
      } catch (error) {
        this.$message.error('评论发布失败：' + error.message)
      }
    },
    
    editComment(comment) {
      this.editingCommentId = comment.id
      this.editingCommentContent = comment.content
    },
    
    cancelEditComment() {
      this.editingCommentId = null
      this.editingCommentContent = ''
    },
    
    async saveEditComment(commentId) {
      if (!this.editingCommentContent.trim()) {
        this.$message.warning('请输入评论内容')
        return
      }
      
      try {
        await this.$axios.put(`/comments/${commentId}`, {
          content: this.editingCommentContent
        })
        
        // 更新本地评论数据
        const index = this.comments.findIndex(c => c.id === commentId)
        if (index !== -1) {
          this.comments[index].content = this.editingCommentContent
        }
        
        this.cancelEditComment()
        this.$message.success('评论更新成功')
      } catch (error) {
        this.$message.error('评论更新失败：' + error.message)
      }
    },
    
    async deleteComment(commentId) {
      this.$confirm('确定要删除这个评论吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.$axios.delete(`/comments/${commentId}`)
          
          // 从本地删除评论
          this.comments = this.comments.filter(c => c.id !== commentId)
          this.$message.success('评论删除成功')
        } catch (error) {
          this.$message.error('评论删除失败：' + error.message)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    // 讨论编辑相关方法
    editDiscussion() {
      this.editForm = {
        packageId: this.discussion.package ? this.discussion.package.id : '',
        title: this.discussion.title,
        content: this.discussion.content
      }
      this.editDialogVisible = true
    },
    
    async saveDiscussion() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await this.$axios.put(`/discussions/${this.$route.params.id}`, this.editForm)
            
            this.discussion = response.data
            this.editDialogVisible = false
            this.$message.success('讨论更新成功')
          } catch (error) {
            this.$message.error('讨论更新失败：' + error.message)
          }
        }
      })
    },
    
    async deleteDiscussion() {
      this.$confirm('确定要删除这个讨论吗？删除后将无法恢复。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        try {
          await this.$axios.delete(`/discussions/${this.$route.params.id}`)
          this.$message.success('讨论删除成功')
          this.$router.push('/discussions')
        } catch (error) {
          this.$message.error('讨论删除失败：' + error.message)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.discussion-detail-page {
  padding: 24px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.error-state {
  text-align: center;
  padding: 60px;
  color: #8c8c8c;
}

.discussion-card {
  margin-bottom: 24px;
}

.discussion-header {
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 16px;
}

.discussion-header h1 {
  margin: 0 0 12px 0;
  font-size: 24px;
  color: #262626;
}

.discussion-meta {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  color: #8c8c8c;
  font-size: 14px;
}

.author-name {
  margin-left: 8px;
  font-weight: 500;
  color: #595959;
}

.time-info {
  margin-left: 16px;
}

.updated-info {
  color: #faad14;
}

.package-link {
  margin-bottom: 12px;
}

.discussion-actions {
  display: flex;
  gap: 8px;
}

.discussion-content {
  font-size: 16px;
  line-height: 1.8;
  color: #262626;
  white-space: pre-wrap;
}

.comments-card {
  margin-top: 24px;
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.comment-form {
  margin-bottom: 24px;
}

.no-comments {
  text-align: center;
  padding: 40px;
  color: #8c8c8c;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.comment-item {
  display: flex;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-content {
  flex: 1;
}

.comment-meta {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.comment-author {
  font-weight: 500;
  color: #595959;
  margin-right: 16px;
}

.comment-time {
  color: #8c8c8c;
}

.comment-actions {
  margin-left: auto;
}

.comment-text {
  line-height: 1.6;
  color: #262626;
}

.comment-edit {
  background-color: #fafafa;
  padding: 12px;
  border-radius: 4px;
}
</style>